
/**
 * Created by 郝梓淳 on 2017/8/31.
 */
/**
 * Created by 郝梓淳 on 2017/8/22.
 */
var superagent = require('superagent')
var cheerio = require("cheerio")
var crypto = require("crypto")
var jluInfo = require("./jluInfo")

//课表请求头
var termClass = {tag: "teachClassStud@schedule", branch: "default", params: {termId:"", studId:""}}
//最新成绩请求头
var latestScore ={tag: "archiveScore@queryCourseScore", branch: "latest", params: {}, rowLimit:""}
//学期成绩请求头
var yearScore = {tag: "archiveScore@queryCourseScore", branch: "byTerm", params: {studId: "", termId: ""}}
//总成绩
var totalScore= {type: "search", tag: "archiveScore@queryCourseScore", branch: "byYear", params: {studId: ""}}

var jluUrl = {
    log: "http://uims.jlu.edu.cn/ntms/j_spring_security_check",
    studentInfo: "http://uims.jlu.edu.cn/ntms/action/getCurrentUserInfo.do",
    learnInfo:"http://uims.jlu.edu.cn/ntms/service/res.do",
}

function jluquery() {} //查询原型
function jluUnit() {}  //工具原型
//Md5加密密码
jluUnit.prototype.Md5 = function (user, psw) {
    var md5 = new crypto.createHash('md5')
    md5.update('UIMS' + user + psw)
    var r_hex = md5.digest('hex')
    return r_hex
}

//处理用户信息 code不为0时成功
jluUnit.prototype.UserInfo=function (info) {
    var UserInfo={
        code:0,
        type:"userInfo",
        name:"",
        studId:"",
        term:"",
        schId:"",
        schName:"",
        cookie:""
    }
    if(info.nickName){
        UserInfo.code=200
        UserInfo.name=info.nickName
        UserInfo.studId = info.userId
        UserInfo.term=info.defRes.teachingTerm
        UserInfo.schId = info.defRes.school
        UserInfo.schName = this.getSchName(info.defRes.school)
    }
    return UserInfo
}

//获取用户专业名，用到jluInfo数据
jluUnit.prototype.getSchName=function (schId) {
    var name = ""
    jluInfo.major.map((node,idx)=>{
        if(node.schId ==schId){
            name =  node.schoolName
            return
        }
    })
    return name
}
//获取用户课表
jluUnit.prototype.getUserCourse =function (item) {
    var totalCourse=[{}
        ,{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },{
            dayOfWeek_1:[],
            dayOfWeek_2:[],
            dayOfWeek_3:[],
            dayOfWeek_4:[],
            dayOfWeek_5:[],
            dayOfWeek_6:[],
            dayOfWeek_7:[],
        },]
    //获取节数
    function extractTime(name) {
        var name = name.match(/第(.*?)节/)[1]
        name = name.split(",")
        return name
    }
    //获取星期
    function extractWeek(begin,end) {
        var week = []
        for(var i=begin;i<=end;i++){
            i-=0
            week.push(i)
        }
        return week
    }
    //一次遍历
    item.map(function (node_0,idx_0) {
        node_0.teachClassMaster.lessonSchedules.map(function (node_1,idx) {
            var lesson={
                name:"",
                classRoom:"",
                teacherName:"",
                time:[],
                week:[],
                dayOfWeek:""
            }
            //获取课程名称
            lesson.name=node_0.teachClassMaster.lessonSegment.fullName
            //获取课程地点
            lesson.classRoom=node_1.classroom.fullName
            //获取课程教师
            lesson.teacherName=node_0.teachClassMaster.lessonTeachers[0].teacher.name
            //提取课程节数
            lesson.time = extractTime(node_1.timeBlock.name)
            //提取周数
            lesson.week= extractWeek(node_1.timeBlock.beginWeek,node_1.timeBlock.endWeek)
            //获取星期
            lesson.dayOfWeek = node_1.timeBlock.dayOfWeek
            // 遍历添加至周对象
            // console.log(lesson)
            lesson.week.map(function (node,idx) {
                totalCourse[node]["dayOfWeek_"+lesson.dayOfWeek].push(lesson)
            })
        })
    })
    return totalCourse
}

//获取用户成绩
jluUnit.prototype.getUserScore=function(item) {
    //构建用户成绩列表
    var score = []

    item.map(function (node,idx) {
        var scoreItem ={
            term:node.teachingTerm.termName,
            name:node.course.courName,
            score:node.score,
            gpoint:node.gpoint,
            credit:node.credit,
            isReselect:node.isReselect
        }
        score.push(scoreItem)
    })
    return score
}

// postLearnInfo

var jluUnit = new jluUnit()


//获取cookie函数，传递从服务器获得的数据
jluquery.prototype.getCookie = function (userid, pwd) {
    return new Promise(function (resolve, reject) {
        superagent.post(jluUrl.log).type('form').send({
            j_username: userid,
            j_password: pwd,
        }).redirects(0).end(function (err, response) {
            var cookie = response.headers["set-cookie"]
            resolve(cookie);
        });
    });
}
//获取用户信息函数，处理后传递给下一个
jluquery.prototype.getUserInfo = function (user, psw) {
    var psw = jluUnit.Md5(user, psw)
    var that = this
    return new Promise((resolve, reject) => {
        that.getCookie(user, psw).then((cookie) => {
            var cookie_ = 'alu='+user+';'+cookie
            superagent.post(jluUrl.studentInfo).set("Cookie", cookie_).type('form').end(function (err, response) {
                var userInfo = jluUnit.UserInfo(response.body)
                userInfo.cookie = cookie_
                console.log(userInfo)
                resolve(userInfo)
            })
        })
    })
};
//获取用户课表
jluquery.prototype.getUserCourse = function (user,psw) {
        var that = this
        var type_1 = "course"
        return new Promise((resolve,reject)=>{
            that.getUserInfo(user,psw).then((userInfo)=>{
                // if(userInfo.code == 0 ){
                //     resolve("账号密码错误")
                // }
                // else{
                    var latestScore = {tag: "teachClassStud@schedule", branch: "default", params: {termId:userInfo.term, studId:userInfo.studId}}
                    superagent.post(jluUrl.learnInfo).set("Cookie",userInfo.cookie).type('json').send(latestScore)
                        .redirects(0).end(function (err, response) {
                        var item = JSON.parse(response.text)
                        var userCourse = jluUnit.getUserCourse(item.value)
                        console.log(userCourse)
                        resolve(item)
                    });
                // }
            })
        })
}

jluquery.prototype.getUserScore = function (user,psw,type) {
    var that = this
    var type_1 = "course"
    return new Promise((resolve,reject)=>{
        that.getUserInfo(user,psw).then((userInfo)=>{
            switch(type){
                //最新成绩
                case 1:  scoreInfo ={"tag":"archiveScore@queryCourseScore","branch":"latest","params":{},"rowLimit":15}; break;
                //全部成绩
                case 2:  scoreInfo = {type: "search", tag: "archiveScore@queryCourseScore", branch: "byYear", params: {studId:userInfo.studId}};break;
                default:scoreInfo ={"tag":"archiveScore@queryCourseScore","branch":"latest","params":{},"rowLimit":15};
            }
            superagent.post(jluUrl.learnInfo).set("Cookie",userInfo.cookie).type('json').send(scoreInfo)
                .redirects(0).end(function (err, response) {
                var item = JSON.parse(response.text)
                var score = jluUnit.getUserScore(item.value)
                // console.log(score)
                resolve(score)
            });
        })
    })
}

// var jluquery = new  jluquery()
// jluquery.getUserScore(54150107,"061538")


module.exports = jluquery;
